<template>
  <tbc-dialog :title="(form.warehouse_id ? '编辑':'添加') + '版本'" ref="dialog" @confirm="formSubmit">
    <tbc-dynamic-form :form="dynamicForm" class="compact">

    </tbc-dynamic-form>
  </tbc-dialog>
</template>

<script lang="ts">
import {defineComponent, reactive, ref, Ref, toRefs} from 'vue'
import useVersion from './api/version'

export default defineComponent({

  name: "app-template-form",


  emits: ['success'],

  setup(props, {emit}) {

    const version = useVersion()
    const dialog: Ref = ref(null)
    const state = reactive({
      dynamicForm: [],
      dynamicBase: [
        {label: '模板名称', value: '', type: 'input', field: 'template_name'},
        {label: '页面路径', value: '', type: 'input', field: 'template_name'},
        {label: '模板图例', value: '', type: 'input', field: 'download_url'},
        {
          label: '开启更新', value: 1, type: 'radio', field: 'status', options: [
            {label: '开启', value: 1},
            {label: '关闭', value: 2},
          ]
        },
      ],
      form: {warehouse_id: '', contact_number: '', address: ''},
      loading: false
    })

    const show = (data: { [k: string]: string | number }): void => {
      state.dynamicForm = JSON.parse(JSON.stringify(state.dynamicBase))
      dialog.value.show()
      if (typeof data === 'undefined') return
      for (let i in (state.dynamicForm as unknown as Record<string, number | string>[])) {
        let item: Record<string, any> = state.dynamicForm[i]
        if (data[item.field]) item.value = data[item.field]
        if (item.field === 'region') {
          item.value = [data.province, data.city, data.district]
        }
      }
      for (let i in state.form as { [k: string]: string | number }) {
        state.form[i] = data[i] as any
      }
    }

    const formSubmit = async (): Promise<void> => {
      let form = JSON.parse(JSON.stringify(state.form));
      (state.dynamicForm as Record<string, number | string>[]).forEach(item => form[item.field] = item.value)
      form.province = form.region.shift() || '';
      form.city = form.region.shift() || '';
      form.district = form.region.shift() || '';
      const res = await version.update(form)
      if (res.data.code === 0) {
        dialog.value.close()
        emit('success')
      }
    }

    return {dialog, show, ...toRefs(state), formSubmit}
  }
})
</script>